﻿#ifndef GLOBAL_H
#define GLOBAL_H
#include <QObject>
#include <QPixmap>
#include <QImage>
#include <QFile>
#include <QApplication>
#include <QSound>
#include <QTime>
#include <QDesktopWidget>

#include "MyApp.h"
class myHelper : public QObject {
    Q_OBJECT
public:

    // 设置样式
    static void setStyle(const QString &style) {
        QFile file(":/qss/resource/qss/" + style + ".css");
        file.open(QIODevice::ReadOnly);
        qApp->setStyleSheet(file.readAll());
        file.close();
    }

    //延时
    static void Sleep(int ms)
    {
        QTime dieTime = QTime::currentTime().addMSecs(ms);
        while( QTime::currentTime() < dieTime )
            QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
    }

    // 灰度
    static QPixmap ChangeGrayPixmap(const QImage &image)
    {
        QImage newImage = image;
        if (newImage.isNull())
        {
            return QPixmap();
        }

        QColor oldColor;

        for(int x = 0; x < newImage.width(); x++){
            for(int y = 0; y < newImage.height(); y++){
                oldColor = QColor(newImage.pixel(x,y));
                //平均值法：Gray=（R+G+B）/3;
                int average = (oldColor.red() + oldColor.green() + oldColor.blue()) / 3;
                newImage.setPixel(x, y, qRgb(average, average, average));
            }
        }

        return QPixmap::fromImage(newImage);
    }

    // 播放声音
    static void PlaySound(const QString &name)
    {
        QString strSound = MyApp::m_strSoundPath + name + ".wav";
        if (!QFile::exists(strSound)) return;
        QSound::play(strSound);
    }

    //返回窗体居中显示的坐标
    static QPoint FormInCenter(QWidget *frm)
    {
        int screenX = qApp->desktop()->availableGeometry().width();
        int screenY = qApp->desktop()->availableGeometry().height()-60;
        int wndX = frm->width();
        int wndY = frm->height();
        QPoint movePoint((screenX-wndX)/2,(screenY-wndY)/2);
        return movePoint;
    }

    //获取屏幕分辨率
    static QSize GetScreenInfo()  //得到当前计算机的屏幕分辨率
    {
        QDesktopWidget* desktopWidget = QApplication::desktop();
        QRect screenRect = desktopWidget->screenGeometry();
        return screenRect.size();
    }

};

#endif // GLOBAL_H

